package com.yingside.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestLoginFrame extends JFrame {

    private JLabel lblUsername,lblPassword;
    private JTextField txtUsername;
    private JPasswordField txtPassword;
    private JButton btnLogin,btnCancel;
    private JPanel p1,p2,p3;
    private String username = "admin";
    private String password = "123456";

    public JTextField getTxtUsername() {
        return txtUsername;
    }

    /*public void setTxtUsername(JTextField txtUsername) {
        this.txtUsername = txtUsername;
    }*/

    public void modifyInputField(String text){
        this.getTxtUsername().setText(text);
    }


    public TestLoginFrame(){
        this.setTitle("登录页面");
        this.setBounds(300,300,400,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(3,1,5,5));
        lblUsername = new JLabel("用户名:");
        lblPassword = new JLabel("密码:");
        txtUsername = new JTextField(20);
        txtPassword = new JPasswordField(20);
        btnLogin = new JButton("登录");
        btnCancel = new JButton("取消");
        p1 = new JPanel();
        p1.add(lblUsername);
        p1.add(txtUsername);
        p2 = new JPanel();
        p2.add(lblPassword);
        p2.add(txtPassword);
        p3 = new JPanel();
        p3.add(btnLogin);
        p3.add(btnCancel);

        btnLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String user = txtUsername.getText();
                char[] pass = txtPassword.getPassword();
                if("".equals(user)){
                    JOptionPane.showMessageDialog(null,"用户名不能为空");
                    //grabFocus()输入框获取光标焦点
                    txtUsername.grabFocus();
                    return;
                }
                if(pass.length == 0){
                    JOptionPane.showMessageDialog(null,"密码不能为空");
                    txtPassword.grabFocus();
                    return;
                }

                String p = new String(pass);

                if(username.equals(user) && password.equals(p)){
                    JOptionPane.showMessageDialog(null,"登录成功,进入主界面");
                    //进入主界面
                    TestMainFrame mainFrame = new TestMainFrame(TestLoginFrame.this);//注意内部类中使用this的情况
                    mainFrame.setVisible(true);
                    //mainFrame.setUsername(user);
                }
                else{
                    JOptionPane.showMessageDialog(null,"登录失败,用户名或者密码出错");
                }

            }
        });


        this.add(p1);
        this.add(p2);
        this.add(p3);

        //pack是打包的意思，其实就是让里面的控件紧凑
        pack();
    }

    public static void main(String[] args) {
        TestLoginFrame loginFrame = new TestLoginFrame();
        loginFrame.setVisible(true);
    }
}
